/**
 * @description 判断括号是否匹配
 * @author 李子一
 */

export function matchBracket(str: string): boolean {
	const length = str.length
	if (!length) {
		return true
	}

	const stack = []

	const leftSymbols = '{(['
	const rightSymbols = '})]'
	const match = (top: string, s: string): boolean => {
		if (top === '{' && s === '}') {
			return true
		}
		if (top === '(' && s === ')') {
			return true
		}
		if (top === '[' && s === ']') {
			return true
		}
		return false
	}

	for (let i = 0; i < length; i++) {
		const s = str[i]
		if (leftSymbols.includes(s)) {
			stack.push(s)
		} else if (rightSymbols.includes(s)) {
			const top = stack[stack.length - 1]

			if (match(top, s)) {
				stack.pop()
			} else {
				return false
			}
		}
	}
	return !stack.length
}

// 功能测试
const str = '{a(b[c])d)e}f'

console.log(matchBracket(str))

const validBracket = (str: string): boolean => {
	if (!str) {
		return true
	}
	const leftSymbols = '([{'
	const rightSymbols = ')]}'
	const stack = []

	const map = {
		'[': ']',
		'(': ')',
		'{': '}'
	}

	for (let i = 0; i < str.length; i++) {
		const char = str[i]
		if (leftSymbols.includes(char)) {
			stack.push(char)
		} else if (rightSymbols.includes(char)) {
			const top = stack[stack.length - 1]
			if (map[top] === ']' || map[top] === ')' || map[top] === '}') {
				stack.pop()
			} else {
				return false
			}
		}
	}

	return !stack.length
}
